#include "app.h"
#include "driver_wireless.h"
#include "dirver_dht11.h"
#include "serial.h"
#include <stdio.h>
#include "delay.h"
#include "oled.h"
#include "oledfont.h"
#include "mq.h"
#include "adc.h"
#include "beep.h"

//温湿度数据
DHT11_Data_TypeDef DHT11_Data;

//温度阈值
float temp_t;
//湿度阈值
float humi_t;
//mq2阈值
float mq2_t;
//mq5阈值
float mq5_t;

MQ mq;

//app初始化
void app_init(void){
	//初始化时钟
	DWT_delay_init();
	//初始化mq2
//	HAL_ADCEx_Calibration_Start(&hadc1);
	
	
	// 初始化串口
	Serial_Init();
	
	// 初始化wifi
	printf("WIFI init...\r\n");
	wireless_init();
	
	//wifi初始化成功
	if(WirelessStatus.initFlag == 1){
		printf("wifi connect successful\r\n");
		HAL_Delay(1000);
	}
}

//loop
void myapp(void){
	
	//定期上报数据
	if(uwTick >= 2000){
			uwTick = 0;
			mq = get_mq();
			if(DHT11_REC_Data(&DHT11_Data) == 1){
				floatValues[0] = DHT11_Data.temp_dec * 0.01 + DHT11_Data.temp_int;
				floatValues[1] = DHT11_Data.humi_dec * 0.01 + DHT11_Data.humi_int;
				floatValues[2] = mq.mq2_value;
				floatValues[3] = mq.mq5_value;
				if(HAL_GPIO_ReadPin(LED_GPIO_Port,LED_Pin) == GPIO_PIN_SET)	boolValue[0] = 1;
				else boolValue[0] = 0;
				wireless_publish_data(0, intIdf, intValue, 4, floatIdentifiers, floatValues, 1, boolIdf, boolValue, 0, stringIdentifiers, stringValues);
			}
		}
	
		//监听数据下发
		if(wireless_get_receive_flag() == W_OK)		//接收数据
		{
			wireless_receiver_command();			//接收命令的操作
		}
		
		if(wireless_get_command_flag() == W_OK)		//在接收数据后，判断是不是接收到command指令
		{
			wireless_command_control();				//命令控制操作
		}
		if(floatValues[0] < temp_t || floatValues[1] < humi_t || floatValues[2] < mq2_t || floatValues[3] < mq5_t)
			beep_ON();
		else beep_OFF();
		
		test();
}

void test(void){
	OLED_ShowString(0,0,"temp:",12,0);
	OLED_Showdecimal(90,0,floatValues[0],2,2,12,0);
	OLED_ShowString(0,2,"humi:",12,0);
	OLED_Showdecimal(90,2,floatValues[1],2,2,12,0);
	OLED_ShowString(0,4,"mq2:",12,0);
	OLED_Showdecimal(90,4,floatValues[2],2,2,12,0);
	OLED_ShowString(0,6,"mq5:",12,0);
	OLED_Showdecimal(90,6,floatValues[3],2,2,12,0);
//	OLED_ShowString(0,0,"UNICORN_LI",16, 1);    //反相显示8X16字符串
// OLED_ShowString(0,2,"unicorn_li_123",12,0);//正相显示6X8字符串
 
// OLED_ShowCHinese(0,4,0,1); //反相显示汉字“独”
// OLED_ShowCHinese(16,4,1,1);//反相显示汉字“角”
// OLED_ShowCHinese(32,4,2,1);//反相显示汉字“兽”
// OLED_ShowCHinese(0,6,0,0); //正相显示汉字“独”
// OLED_ShowCHinese(16,6,1,0);//正相显示汉字“角”
// OLED_ShowCHinese(32,6,2,0);//正相显示汉字“兽”

// OLED_ShowNum(48,4,6,1,16, 0);//正相显示1位8X16数字“6”
// OLED_ShowNum(48,7,77,2,12, 1);//反相显示2位6X8数字“77”
// OLED_DrawBMP(90,0,122, 4,BMP1,0);//正相显示图片BMP1
// OLED_DrawBMP(90,4,122, 8,BMP1,1);//反相显示图片BMP1
// 
// OLED_HorizontalShift(0x26);//全屏水平向右滚动播放
}